export class LocalDataManager {
  name = ''
  validity = ''
  static _existNames: any
  constructor(name: string, validity?: any) {
    // 抛出重复的名称错误
    const existNames = LocalDataManager._existNames
    if (!existNames.includes(name)) {
      existNames.push(name)
    }
    /* if (existNames.includes(name)) {
      throw `本地缓存错误：${name} 名称重复`
    } else {
      existNames.push(name)
    } */
    this.name = name
    this.validity = validity
  }

  update(data: any) {
    const old = this.get()
    if (old && old instanceof Object && data instanceof Object) {
      data = Object.assign(old, data)
    }
    this.set(data)
  }

  get() {
    const data = getLocalData(this.name)
    if (data && (data.expires > Date.now() || !data.expires)) {
      return data.data
    } else {
      this.clear()
      return null
    }
  }

  // 设置
  set(data: any) {
    let result: any = {}
    result.data = data
    if (this.validity) {
      result.expires = Date.now() + this.validity
    }
    console.log(this.name, result)
    setLocalData(this.name, result)
  }

  // 清理
  clear() {
    clearLocalData(this.name)
  }
}

LocalDataManager._existNames = []

function getLocalData(name: string) {
  const data = uni.getStorageSync(name)
  if (data) {
    return JSON.parse(data)
  } else {
    return data
  }
}

function setLocalData(name: string, data: any) {
  uni.setStorageSync(name, JSON.stringify(data))
}

function clearLocalData(name: string) {
  uni.removeStorageSync(name)
}
